<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { isLoggedIn, getUserInfo, logout, getAccessToken } from '../utils/auth.js'
import { showToast } from 'vant'

const router = useRouter()
const userInfo = ref(null)
const isUserLoggedIn = ref(false)
const loading = ref(false)

// 统计数据
const stats = ref({
  mileage: 0,
  coupons: 25,
  browseHistory: 0,
  favorites: 0
})

// 订单统计（根据实际数据获取）
const orderStats = ref({
  pendingPayment: 0,
  pendingTravel: 0,
  pendingReview: 0,
  refunds: 0
})

// 实名认证状态
const verifyStatus = ref(0) // 0-未认证, 1-审核中, 2-已认证, 3-审核驳回

onMounted(() => {
  checkLoginStatus()
  if (isLoggedIn()) {
    loadUserData()
  }
})

const checkLoginStatus = () => {
  isUserLoggedIn.value = isLoggedIn()
  if (isUserLoggedIn.value) {
    // 先使用本地存储的用户信息作为初始值
    userInfo.value = getUserInfo()
  }
}

// 从后端API加载用户数据
const loadUserData = async () => {
  if (!isLoggedIn()) {
    return
  }

  const token = getAccessToken()
  if (!token) {
    showToast('未找到登录凭证')
    return
  }

  loading.value = true
  try {
    const response = await fetch('http://localhost:8000/user/idcard/status', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    })

    const result = await response.json()

    if (result.code === 200 && result.data) {
      // 更新用户信息
      userInfo.value = {
        ...userInfo.value,
        nickname: result.data.nickname || userInfo.value?.nickname || '用户',
        avatar: result.data.avatar,
        avatar_url: result.data.avatar, // 兼容前端模板中使用的字段名
        phone: result.data.phone || userInfo.value?.phone || ''
      }
      
      // 更新实名认证状态
      verifyStatus.value = result.data.verify_status || 0
    } else {
      console.error('获取用户信息失败:', result.message)
      // 如果API调用失败，使用本地存储的信息
      if (!userInfo.value) {
        userInfo.value = getUserInfo()
      }
    }
  } catch (error) {
    console.error('获取用户信息出错:', error)
    showToast('获取用户信息失败')
    // 如果API调用失败，使用本地存储的信息
    if (!userInfo.value) {
      userInfo.value = getUserInfo()
    }
  } finally {
    loading.value = false
  }
}

const goToVerifyIdentity = () => {
  if (!isUserLoggedIn.value) {
    showToast('请先登录')
    router.push('/user/login')
    return
  }
  // 根据实名认证状态跳转到不同页面
  if (verifyStatus.value === 1) {
    // 审核中，跳转到审核中页面
    router.push('/pending-verification')
  } else if (verifyStatus.value === 2) {
    // 已认证，跳转到已实名认证成功页面
    router.push('/verified-identity')
  } else {
    // 未认证或审核驳回，跳转到实名认证上传页面
    router.push('/verify-identity')
  }
}

const goToOrders = (type) => {
  if (!isUserLoggedIn.value) {
    showToast('请先登录')
    router.push('/user/login')
    return
  }
  router.push(`/orders?type=${type}`)
}

const goToMileage = () => {
  showToast('功能开发中')
}

const goToCoupons = () => {
  showToast('功能开发中')
}

const goToBrowseHistory = () => {
  showToast('功能开发中')
}

const goToFavorites = () => {
  showToast('功能开发中')
}

const goToLogin = () => {
  router.push('/user/login')
}

const handleLogout = () => {
  logout()
  isUserLoggedIn.value = false
  userInfo.value = null
  verifyStatus.value = 0
  showToast('已退出登录')
}

const goToPersonalInfo = () => {
  if (!isUserLoggedIn.value) {
    showToast('请先登录')
    router.push('/user/login')
    return
  }
  router.push('/personal-info')
}

const goToConsultation = () => {
  if (!isUserLoggedIn.value) {
    showToast('请先登录')
    router.push('/user/login')
    return
  }
  router.push('/consultation')
}
</script>

<template>
  <div class="profile-page">
    <!-- 顶部用户信息区域 -->
    <div class="profile-header">
      <div v-if="isUserLoggedIn" class="user-info-section">
        <div class="avatar-container" @click="goToPersonalInfo">
          <img 
            v-if="userInfo?.avatar || userInfo?.avatar_url" 
            :src="userInfo.avatar || userInfo.avatar_url" 
            :alt="userInfo.nickname" 
            class="avatar-img"
          />
          <div v-else class="avatar-placeholder">
            {{ userInfo?.nickname?.charAt(0) || 'U' }}
          </div>
        </div>
        <div class="user-details">
          <div class="user-name">{{ userInfo?.nickname || '用户' }}</div>
          <div class="user-phone" v-if="userInfo?.phone">{{ userInfo.phone }}</div>
          <div class="verify-status" @click="goToVerifyIdentity">
            <span v-if="verifyStatus === 0" class="verify-badge unverified">
              ⚠️ 未实名认证
            </span>
            <span v-else-if="verifyStatus === 1" class="verify-badge pending">
              ⏳ 审核中
            </span>
            <span v-else-if="verifyStatus === 2" class="verify-badge verified">
              ✅ 已实名认证
            </span>
            <span v-else-if="verifyStatus === 3" class="verify-badge rejected">
              ❌ 审核驳回
            </span>
          </div>
        </div>
        <div class="logout-btn" @click="handleLogout">退出</div>
      </div>
      <div v-else class="login-prompt">
        <div class="prompt-text">请登录后查看个人信息</div>
        <button class="login-btn" @click="goToLogin">立即登录</button>
      </div>
    </div>

    <!-- 统计数据模块 -->
    <div class="stats-module">
      <div class="stats-item" @click="goToMileage">
        <div class="stats-value">{{ stats.mileage }}</div>
        <div class="stats-label">里程</div>
      </div>
      <div class="stats-item" @click="goToCoupons">
        <div class="stats-value">{{ stats.coupons }}</div>
        <div class="stats-label">优惠券</div>
      </div>
      <div class="stats-item" @click="goToBrowseHistory">
        <div class="stats-value">{{ stats.browseHistory }}</div>
        <div class="stats-label">浏览历史</div>
      </div>
      <div class="stats-item" @click="goToFavorites">
        <div class="stats-value">{{ stats.favorites }}</div>
        <div class="stats-label">收藏</div>
      </div>
    </div>

    <!-- 订单快捷入口 -->
    <div class="order-quick-actions">
      <div class="action-item" @click="goToOrders('pending_payment')">
        <div class="action-icon pending-payment">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <rect x="3" y="7" width="18" height="12" rx="2" fill="currentColor"/>
            <path d="M7 11h10M7 15h6" stroke="white" stroke-width="1.5" stroke-linecap="round"/>
          </svg>
        </div>
        <span class="action-label">待支付</span>
      </div>
      <div class="action-item" @click="goToOrders('pending_travel')">
        <div class="action-icon pending-travel">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M3 12h18M3 6h18M3 18h18" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
            <circle cx="18" cy="12" r="2" fill="currentColor"/>
          </svg>
        </div>
        <span class="action-label">已支付</span>
      </div>
      <div class="action-item" @click="goToOrders('pending_review')">
        <div class="action-icon pending-review">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" fill="currentColor"/>
            <circle cx="9" cy="12" r="1" fill="white"/>
            <circle cx="15" cy="12" r="1" fill="white"/>
          </svg>
        </div>
        <span class="action-label">待点评</span>
      </div>
      <div class="action-item" @click="goToOrders('refunds')">
        <div class="action-icon refunds">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <circle cx="12" cy="12" r="10" fill="currentColor"/>
            <path d="M12 8v8M8 12h8" stroke="white" stroke-width="2" stroke-linecap="round"/>
          </svg>
        </div>
        <span class="action-label">退款单</span>
      </div>
      <div class="action-item" @click="goToOrders('all')">
        <div class="action-icon all-orders">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <rect x="3" y="5" width="18" height="14" rx="2" fill="currentColor"/>
            <path d="M3 9h18M7 13h10" stroke="white" stroke-width="1.5" stroke-linecap="round"/>
          </svg>
        </div>
        <span class="action-label">全部订单</span>
      </div>
    </div>

    <!-- 个人信息入口 -->
    <div class="info-section" v-if="isUserLoggedIn">
      <div class="info-item" @click="goToPersonalInfo">
        <div class="info-icon">👤</div>
        <span class="info-text">个人信息</span>
        <span class="info-arrow">></span>
      </div>
      <div class="info-item" @click="goToVerifyIdentity">
        <div class="info-icon">🆔</div>
        <span class="info-text">实名认证</span>
        <span class="info-arrow">></span>
      </div>
      <div class="info-item" @click="goToConsultation">
        <div class="info-icon">💬</div>
        <span class="info-text">在线咨询</span>
        <span class="info-arrow">></span>
      </div>
    </div>
  </div>
</template>

<style scoped>
.profile-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 80px;
}

/* 顶部用户信息区域 */
.profile-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40px 16px 24px;
  color: white;
}

.user-info-section {
  display: flex;
  align-items: center;
  gap: 16px;
}

.avatar-container {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  overflow: hidden;
  border: 3px solid rgba(255, 255, 255, 0.3);
  cursor: pointer;
  flex-shrink: 0;
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  font-weight: 600;
}

.user-details {
  flex: 1;
}

.user-name {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 4px;
}

.user-phone {
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 8px;
}

.verify-status {
  cursor: pointer;
}

.verify-badge {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.verify-badge.unverified {
  background: rgba(255, 193, 7, 0.3);
  color: #ffc107;
}

.verify-badge.pending {
  background: rgba(33, 150, 243, 0.3);
  color: #2196f3;
}

.verify-badge.verified {
  background: rgba(76, 175, 80, 0.3);
  color: #4caf50;
}

.verify-badge.rejected {
  background: rgba(244, 67, 54, 0.3);
  color: #f44336;
}

.logout-btn {
  padding: 6px 16px;
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 16px;
  color: white;
  font-size: 14px;
  cursor: pointer;
}

.login-prompt {
  text-align: center;
  padding: 20px 0;
}

.prompt-text {
  font-size: 16px;
  margin-bottom: 16px;
  opacity: 0.9;
}

.login-btn {
  padding: 10px 24px;
  background: white;
  color: #667eea;
  border: none;
  border-radius: 20px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
}

/* 统计数据模块 */
.stats-module {
  background: white;
  margin: 16px;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  justify-content: space-around;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stats-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  transition: transform 0.2s;
}

.stats-item:active {
  transform: scale(0.95);
}

.stats-value {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.stats-label {
  font-size: 12px;
  color: #666;
}

/* 订单快捷入口 */
.order-quick-actions {
  background: white;
  margin: 16px;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  justify-content: space-around;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  transition: transform 0.2s;
}

.action-item:active {
  transform: scale(0.95);
}

.action-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
}

.action-icon svg {
  width: 28px;
  height: 28px;
}

.action-icon.pending-payment {
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
}

.action-icon.pending-travel {
  background: linear-gradient(135deg, #51cf66, #40c057);
}

.action-icon.pending-review {
  background: linear-gradient(135deg, #4dabf7, #339af0);
}

.action-icon.refunds {
  background: linear-gradient(135deg, #ffa94d, #ff922b);
}

.action-icon.all-orders {
  background: linear-gradient(135deg, #9775fa, #845ef7);
}

.action-label {
  font-size: 12px;
  color: #333;
  font-weight: 500;
}

/* 个人信息入口 */
.info-section {
  background: white;
  margin: 16px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.info-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background 0.2s;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item:active {
  background: #f5f5f5;
}

.info-icon {
  font-size: 20px;
  margin-right: 12px;
}

.info-text {
  flex: 1;
  font-size: 15px;
  color: #333;
}

.info-arrow {
  color: #999;
  font-size: 16px;
}
</style>

